﻿using System;
using System.Web.Script.Serialization;

namespace scripts.net
{
    public class BaseMsg
    {
        //协议名
        public string protoName = "";

        //编码器
        private static JavaScriptSerializer Js = new JavaScriptSerializer();

        //协议名编码
        public static byte[] ProtoNameEncode(BaseMsg baseMsg)
        {
            byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(baseMsg.protoName);
            //获取协议名转换后的长度
            Int16 len = (Int16) nameBytes.Length;
            byte[] newBytes = new byte[len + 2];
            newBytes[0] = (byte) (len % 256);
            newBytes[1] = (byte) (len / 256);
            //将长度组合在一起并返回
            Array.Copy(nameBytes, 0, newBytes, 2, len);
            return newBytes;
        }

        //协议名解码
        public static string ProtoNameDecode(byte[] bytes, int idx, out int cnt)
        {
            cnt = 0;
            //数据必须大于2字节才是有用的
            if (idx + 2 > bytes.Length)
            {
                return "";
            }

            Int16 len = (Int16) ((bytes[idx + 1] << 8) | bytes[idx]);
            if (len <= 0)
            {
                return "";
            }

            //接收到的数据长度 比指定的数据长度len大 才有用
            if (idx + 2 + len > bytes.Length)
            {
                return "";
            }

            cnt = len + 2;
            string name = System.Text.Encoding.UTF8.GetString(bytes, idx + 2, len);
            return name;
        }

        //编码
        public static byte[] Encode(BaseMsg baseMsg)
        {
            string s = Js.Serialize(baseMsg);
            return System.Text.Encoding.UTF8.GetBytes(s);
        }

        //解码
        public static BaseMsg Decode(string protoName, byte[] bytes, int idx, int cnt)
        {
            string s = System.Text.Encoding.UTF8.GetString(bytes, idx, cnt);
            BaseMsg baseMsg = (BaseMsg) Js.Deserialize(s, Type.GetType(protoName));
            return baseMsg;
        }
    }
}